/*
 * @Author: LGX
 * @Date: 2022-03-30 09:51:40
 * @LastEditors: LGX
 * @LastEditTime: 2022-04-11 22:09:10
 * @FilePath: \erp-management-system\src\views\seas\CustomerAdd.jsx
 * @Description: 新增客户公海
 * 
 */
import React, { useState, useEffect, memo } from 'react'
import { Form, Input, Button, Select, DatePicker, Rate, Space, Cascader, Modal, Row, Col, message } from 'antd';
import { PlusSquareFilled } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import chinaDivision from '../../utils/chinaDivision';
import myAxios from '../../utils/myAxios'
import GoodsCategory from '../../views/customerManage/add/GoodsCategory'; //商品分类选择组件
import AddOption from '../../views/customerManage/add/addOption/AddOption'; //商品分类选择组件
import axios from '../../utils/http'
import store from '../../redux/store';
import { AsyncGetOptionAction } from '../../redux/action/customerAction/option';
import moment from 'moment';
const { TextArea } = Input;
const { Option } = Select;

function Customeradd(props) {
    const { status } = props
    console.log(status);
    //当前是新增还是修改
    const [operationState, setoperationState] = useState(status ? status : '');
    const navigate = useNavigate();
    //所有select框的值
    const [jobList, setjobList] = useState([]);
    const [customerType, setcustomerType] = useState([]);
    const [customerSource, setcustomerSource] = useState([]);
    const [customerIndustry, setcustomerIndustry] = useState([]);
    const [customerLevel, setcustomerLevel] = useState([]);
    const [bigClass, setbigClass] = useState([]);
    const [smallClass, setsmallClass] = useState([]);
    const [isModalVisible, setisModalVisible] = useState(false);
    const [toAddOptionData, settoAddOptionData] = useState([]);
    //写一个方法，来处理商品分类
    function bC(arr) {
        let tempArr = []
        arr.forEach(element => {
            tempArr.push(element.bigClass)
        });
        return tempArr
    }
    const onSecondCityChange = value => {
        // setSecondCity(value);
    };
    //修改
    const updata = () => {

    }
    //初始化，获取所有下拉选项
    useEffect(() => {
        // 获取所有下拉的异步action
        store.dispatch(AsyncGetOptionAction())

        let fn = store.subscribe(() => {
            setjobList(store.getState().customerReducer.optionReducer.customerPosition)
            setcustomerType(store.getState().customerReducer.optionReducer.customerType)
            setcustomerSource(store.getState().customerReducer.optionReducer.customerSource)
            setcustomerIndustry(store.getState().customerReducer.optionReducer.customerIndustry)
            setcustomerLevel(store.getState().customerReducer.optionReducer.customerLevel)
            setbigClass(bC(store.getState().customerReducer.optionReducer.comSort))
        })
        return () => {
            fn()
        }
    }, [])

    //点击新增的函数
    function addOption(type, value) {
        //形参type  是点击新增职位，或者新增客户来源 等 的一种标识
        // jobList：表示 新增职位 ，customerType：表示 新增客户类型 ，customerLevel ：表示新增客户级别 ，  customerSource ：表示新增客户来源

        //根据不同的type做判断，点击保存的时候需要去请求不同的接口
        console.log(type);
        settoAddOptionData(value)
    }
    //选择了大类以后，再去请求对应小类的数据
    const handleProvinceChange = value => {
        //修改了大类之后，需要把之前选择的小类选项置空
        form.setFieldsValue({
            smallClass: ''
        })
        myAxios({
            method: 'get',
            url: '/customer/customerComSort/findSmallClass',
            headers: {
                'isLoading': false
            },
            params: { bigClass: value }
        })
            .then(res => {
                console.log(res.data.data);
                let tempArr = []
                res.data.data.forEach(item => {
                    tempArr.push(item.smallClass)
                })
                setsmallClass(tempArr);
                // setCities(smallClass[value]);
            })

    };
    //保存按钮
    const onFinish = (values) => {
        //对日期控件进行数据处理
        let newValue
        if (values['birthDay']) {
            newValue = {
                ...values,
                birthDay: values['birthDay'].format('YYYY-MM-DD'),
            }
        } else {

            newValue = values;
        }
        if (!status) {
            newValue = { ...newValue, employeeInputName: '管理员', applyPerson: '超级管理员', entryTime: moment(new Date()).format('YYYY-MM-DD h:mm:ss') }
        } else {
            newValue = { ...newValue, employeeInputName: '管理员', applyPerson: '超级管理员', updateTime: moment(new Date()).format('YYYY-MM-DD h:mm:ss') }
        }
        console.log(newValue);
        //请求成功跳转公海列表
        myAxios({
            url: 'gongHai/insertPublicCustomer',
            method: 'post',
            data: newValue,
            headers: {
                isLoading: 'false'
            }
        }).then(res => {
            const { data, code, msg } = res.data
            if (code === 200) {
                console.log(data);
                message.success('添加客户公海成功')
                setTimeout(() => {
                    navigate('/seas/list')
                }, 1500)
            } else {
                message.error(msg)
            }
        })
            .catch(err => {
                console.log(err);
            })
    }
    //表单填写失败
    const onFinishFailed = (errorInfo) => {
        message.error('必填信息未填写');
    }

    const [form] = Form.useForm();

    //省市区选择部分
    function onChange(value) {
        console.log(value);
    }

    const handleOk = () => {
        setisModalVisible(false);
    };

    const handleCancel = () => {
        setisModalVisible(false);
    };
    //
    // console.log(status);
    var defaultForm = {}
    form.setFieldsValue(defaultForm)
    const options = chinaDivision
    if (status) {
        defaultForm = {
            customerUsername: status.customerUsername,
            customerName: status.customerName,
            ustomerPositionId: status.ustomerPositionId,
            phoneNumber: status.phoneNumber,
            birthDay: moment(new Date(status.birthDay)).add(8, 'hour'),
            qqNumber: status.qqNumber,
            email: status.email,
            // region:status.,
            address: status.address,
            postal: status.postal,
            website: status.website,
            customerTypeId: status.customerTypeTitle,
            customerLevelId: status.customerLevelTitle,
            customerSourceId: status.customerSourceTitle,
            customerIndustryId: status.industryTitle,
            comSortName1:status.comSortName1,
            comSortName1:status.comSortName2,
            comSortId: status.comSort,
            customerPositionId:status.customerPositionId,
            remarks: status.remarks,
            website: status.website,
            region: [status.province, status.city, status.area]
        }
        console.log(status.industryTitle);
    }
    return (
        <>
            <Form
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 12, }}
                layout="horizontal"
                size='small'
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                form={form}
                initialValues={{ ...defaultForm }}
            >
                <Row justify='space-around' gutter={4}>
                    <Col span={10}>
                        <Form.Item label="客户名称" name="customerUsername">
                            <Input />
                        </Form.Item>
                        <Form.Item label="联系人" name='customerName'>
                            <Input />
                        </Form.Item>

                        <Form.Item label="职位" >
                            <Space >
                                <Form.Item name='customerPositionId'>
                                    <Select placeholder="请选择">
                                        {
                                            jobList.map((item) =>
                                                <Select.Option key={item.id} value={item.id}>{item.title}</Select.Option>
                                            )
                                        }
                                    </Select>
                                </Form.Item>
                                <Form.Item>
                                    <Button onClick={() => {
                                        setisModalVisible(true)
                                        addOption('jobList', jobList)
                                    }


                                    } icon={<PlusSquareFilled />} style={{ backgroundColor: '#5CAD69', color: 'white' }}>
                                        新增
                                    </Button>
                                </Form.Item>
                            </Space>
                        </Form.Item>
                        <Form.Item label="手机号码" name='phoneNumber'
                            rules={[
                                {
                                    pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '请输入正确的手机号'
                                },
                                {
                                    required: true,
                                    message: '请输入手机号码',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item label="生日" name='birthDay'>
                            <DatePicker />
                        </Form.Item>
                        <Form.Item label="QQ" name="qqNumber">
                            <Input />
                        </Form.Item>
                        <Form.Item label="电子邮箱" name="email"
                            rules={[
                                {
                                    type: 'email',
                                    message: '请输入正确的邮箱地址！',
                                },
                                {
                                    required: true,
                                    message: '请输入邮箱地址',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item label="所在地区" name="region" >
                            <Cascader options={options} onChange={onChange} placeholder="请选择" />
                        </Form.Item>

                        <Form.Item label="详细地址" name="address"  >
                            <Input />
                        </Form.Item>
                        <Form.Item label="邮编" name="postal">
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={10} >
                        <Form.Item label="网址" name="website">
                            <Input />
                        </Form.Item>

                        <Form.Item label="客户类型" >
                            <Space>
                                <Form.Item name='customerTypeId'>
                                    <Select placeholder="请选择" style={{ width: '170px' }}>
                                        {
                                            customerType.map((item) =>
                                                <Select.Option key={item.id} value={item.id}>{item.title}</Select.Option>
                                            )
                                        }
                                    </Select>
                                </Form.Item>
                                <Form.Item>
                                    <Button icon={<PlusSquareFilled />} style={{ backgroundColor: '#5CAD69', color: 'white' }}
                                        onClick={() => {
                                            setisModalVisible(true)
                                            addOption('customerType', customerType)
                                        }}
                                    >新增</Button>
                                </Form.Item>
                            </Space>
                        </Form.Item>
                        <Form.Item label="客户级别">
                            <Space>
                                <Form.Item name='customerLevelId'>
                                    <Select placeholder="请选择" style={{ width: '170px' }}>
                                        {
                                            customerLevel.map((item) =>
                                                <Select.Option key={item.id} value={item.id}>
                                                    {/* <Rate count={item} disabled value={item} /> */}
                                                    <span>
                                                        {item.title}
                                                    </span>
                                                </Select.Option>
                                            )
                                        }
                                    </Select>
                                </Form.Item>
                                <Form.Item>
                                    <Button icon={<PlusSquareFilled />} style={{ backgroundColor: '#5CAD69', color: 'white' }}
                                        onClick={() => {
                                            setisModalVisible(true)
                                            addOption('customerLevel', customerLevel)
                                        }}
                                    >新增</Button>
                                </Form.Item>
                            </Space>
                        </Form.Item>
                        <Form.Item label="客户来源" >
                            <Space>
                                <Form.Item name='customerSourceId'>
                                    <Select placeholder="请选择" style={{ width: '170px' }}>
                                        {
                                            customerSource.map((item) =>
                                                <Select.Option key={item.id} value={item.id}>{item.title}</Select.Option>
                                            )
                                        }
                                    </Select>
                                </Form.Item>
                                <Form.Item>
                                    <Button icon={<PlusSquareFilled />} style={{ backgroundColor: '#5CAD69', color: 'white' }}
                                        onClick={() => {
                                            setisModalVisible(true)
                                            addOption('customerSource', customerSource)
                                        }}
                                    >新增</Button>
                                </Form.Item>
                            </Space>
                        </Form.Item>
                        <Form.Item label="所属行业" name='customerIndustryId'

                        >
                            <Select placeholder="请选择">
                                {
                                    customerIndustry.map((item) =>
                                        <Select.Option key={item.id}>{item.title}</Select.Option>
                                    )
                                }
                            </Select>

                        </Form.Item>
                        <Form.Item label="商品类别" >
                            <Space>
                                <Form.Item name='comSortName1'>
                                    <Select placeholder='请选择' style={{ width: 120 }} onChange={handleProvinceChange}>
                                        {bigClass.map(province => (
                                            <Option key={province}>{province}</Option>
                                        ))}
                                    </Select>
                                </Form.Item>
                                <Form.Item name='comSortName2'>
                                    <Select style={{ width: 120 }} placeholder='请选择' onChange={onSecondCityChange}>
                                        {smallClass.map(city => (
                                            <Option key={city}>{city}</Option>
                                        ))}
                                    </Select>
                                </Form.Item>
                            </Space>
                        </Form.Item>
                        <Form.Item label="备注" name="remarks" wrapperCol={{
                            span: 9,
                        }}>
                            <TextArea rows={4} />
                        </Form.Item>
                    </Col>
                </Row>
                {/* 当前为新增状态时才显示 */}
                {!operationState ? <div style={{ textAlign: 'center', marginTop: window.innerHeight * 0.1 }}>
                    <Space size='middle'>
                        <Button style={{ width: 100 }} size='midle' type="primary" htmlType="submit">
                            保存
                        </Button>
                        <Button onClick={() => { form.resetFields(); message.success('表单已清空') }} style={{ width: 100 }} size='midle' danger type="primary" >
                            清空
                        </Button>
                    </Space>
                </div> : ''}
            </Form>
            {/* 点击新增职位，新增客户；类型等的模态 */}
            <Modal title='自定义选项值' visible={isModalVisible} onOk={handleOk}
                onCancel={handleCancel}
                footer={[]}
            >
                <AddOption toAddOptionData={toAddOptionData} />
            </Modal>
        </>
    )
}
export default memo(Customeradd) 